import { checkSystemUpdate } from './api/system.js';
import { cusTabBar } from './config';

import { log } from './utils/log';
import { compareVersion } from './utils/util';
import { getToken, setStorageItem } from './utils/storage';
import { getUserInfo } from './api/user';

const watchMapManger = {
  watchMap: new Map(),
  watch(key, watch) {
    let watchList = this.watchMap.get(key);
    if (!watchList) {
      watchList = [];
      this.watchMap.set(key, watchList);
    }
    watchList.push(watch);
  },
  notify(key, value) {
    let watchList = this.watchMap.get(key);
    if (watchList) {
      watchList.forEach((watch) => {
        watch(value);
      });
    }
  },
  unwatch(key, watch) {
    let watchList = this.watchMap.get(key);
    if (watchList) {
      const index = watchList.indexOf(watch);
      if (index > -1) {
        watchList.splice(index, 1);
      }
      if (watchList.length === 0) {
        this.watchMap.delete(key);
      }
    }
  },
};
App({
  log,
  observe(obj, key, { watchKey, watch }) {
    if(!watchKey || !watch) {
      return;
    }
    let val = obj[key];
    watchMapManger.watch(watchKey, watch);
    Object.defineProperty(obj, key, {
      configurable: true,
      enumerable: true,
      set: function (value) {
        val = value;
        watchMapManger.notify(watchKey, value);
      },
      get: function () {
        return val;
      },
    });
  },
  unObserve(watchKey, watch) {
    watchMapManger.unwatch(watchKey, watch);
  },
  onLaunch: function () {
    //检查小程序更新
    checkSystemUpdate();
    this.getCusNavBar();

    if (this.globalData.token) {
      this.initUserInfo();
    }
    this.initHoverVisible();
  },
  initHoverVisible() {},
  onHide: function () {},
  getCusNavBar() {
    // 获取系统状态栏信息
    wx.getSystemInfo({
      success: (e) => {
        this.globalData.StatusBar = e.statusBarHeight;
        let capsule = wx.getMenuButtonBoundingClientRect();
        if (capsule) {
          this.globalData.Custom = capsule;
          this.globalData.CustomBar = capsule.bottom + capsule.top - e.statusBarHeight;
        } else {
          this.globalData.CustomBar = e.statusBarHeight + 50;
        }
        let sdkv = e.SDKVersion;

        this.globalData.sdkv = sdkv;
        this.globalData.deviceInfo = e;
      },
    });
  },
  globalData: {
    token: getToken(), //user token
    invite_key: '',
    isNotPageShow: false, // 防止从其他地方返回 刷新页面
    headerImgPath: '',
    income_rate: '', // 分成比例
    homeNeedRefresh: false, // 首页是否需要刷新
    isH5NeedRefresh: false,
    tabbarShow: true,
    isInNationalTest: false,
  },
  initUserInfo() {
    if (!this.globalData.token) {
      return;
    }
    getUserInfo({
      token: this.globalData.token,
    })
      .then((res) => {
        console.log(res);
        if (res.id) {
          setStorageItem('id', res.id);
        }
        if (res.invite_key) {
          setStorageItem('invite_key', res.invite_key);
        }

        if (res.avator) {
          setStorageItem('headerImgPath', res.avator);
        }
        let user_name = res.user_name || res.emcee_name || res.wx_nickname_xin;
        if (user_name) {
          setStorageItem('user_name', user_name);
        }
        if (res.comment_json) {
          setStorageItem('comment_json', res.comment_json);
        } else {
          setStorageItem('comment_json', '');
        }

        let isSendSystemGift = res.isSendSystemGift;
        if (isSendSystemGift) {
          setStorageItem('isSendSystemGift', isSendSystemGift);
        }
        let isNeedUserComment = res.isNeedUserComment;
        if (isSendSystemGift) {
          setStorageItem('isNeedUserComment', isNeedUserComment);
        }
        if (res.comment_info) {
          setStorageItem('sf_avg', res.comment_info.sf_avg || 5);
        } else {
          setStorageItem('sf_avg', 5);
        }

        if (res.id) {
          setStorageItem('userId', res.id);
        }

        if (res.wx_openid) {
          setStorageItem('openId', res.wx_openid);
        }

        if (res.token) {
          setStorageItem('token', res.token);
        }

        if (res.user_money) {
          setStorageItem('user_money', res.user_money);
          if (res.user_money.invite_key) {
            setStorageItem('invite_key', res.invite_key);
          }
        }

        if (res.income_rate) {
          setStorageItem('income_rate', res.income_rate);
        }

        // 邀请人数
        if (res.invite_pcount) {
          setStorageItem('invite_pcount', res.invite_pcount);
        }
        // vip等级
        if (res.vip_grade) {
          setStorageItem('vip_grade', res.vip_grade);
        }
        //vip 当前经验
        if (res.vip_point) {
          setStorageItem('vip_point', res.vip_point);
        }
        // vip Data
        if (res.vipData) {
          res.vipData.sub_title = res.vipData.title.substring(0, 1);
          setStorageItem('vipData', res.vipData);
        }
        if (res.invite_pcount) {
          // 0 需要弹出神秘红包 1 不需要弹出神秘红包
          setStorageItem('invite_pcount', res.invite_pcount);
        }

        if (res.hhr_type) {
          setStorageItem('hhr_type', res.hhr_type);
        } else {
          setStorageItem('hhr_type', '0');
        }

        if (res?.newCommentInfo?.comment_size) {
          setStorageItem('comment_size', res.newCommentInfo.comment_size);
        } else {
          setStorageItem('comment_size', '0');
        }

        setStorageItem('reserveCount', res?.reserveSize || 0);
      })
      .catch((err) => {});
  },

  //hideTabBar
  hideTabBar() {
    const canUse = compareVersion(this.globalData.sdkv, '2.5.0') > 0;

    if (cusTabBar && canUse) {
      // this.globalData.tabbarShow = false
    } else {
      // wx.hideTabBar({
      //   // animation: true,
      // });
    }
  },
  //showTabBar
  showTabBar() {
    const canUse = compareVersion(this.globalData.sdkv, '2.5.0') > 0;
    if (cusTabBar && canUse) {
      // this.globalData.tabbarShow = true
    } else {
      // wx.showTabBar({
      //   // animation: true,
      // });
    }
  },
});
